/**
 * Copyright (c) 2019 早点下班 All rights reserved.
 * <p>
 * <p>
 * <p>
 * 版权所有，侵权必究！
 */

package me.codegenerator2.rest;

import me.codegenerator2.service.GeneratorMysqlFromExcelService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 代码生成器
 *
 * @author Mark
 */
@RestController
@RequestMapping("/excel/data/generatormysql")
public class GeneratorMysqlFromExcelController {
    @Autowired
    private GeneratorMysqlFromExcelService generatorMysqlFromExcelService;

    @PostMapping(value = "/code", produces = "text/plain;charset=UTF-8")
    public ResponseEntity code(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName, HttpServletResponse response) throws Exception {
        String result = generatorMysqlFromExcelService.generatorMysqlFromExcel(file, tableName);
        return new ResponseEntity<String>(result, HttpStatus.OK);
    }

    @PostMapping(value = "/codecc")
    public ResponseEntity codecc(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName, HttpServletResponse response) throws Exception {
        String result = generatorMysqlFromExcelService.generatorMysqlFromExcel(file, tableName);
        return new ResponseEntity<String>(result, HttpStatus.OK);
    }


    @GetMapping(value = "/aa", produces = "text/plain;charset=UTF-8")
    public ResponseEntity aa() throws Exception {
        String result = "我饿们是你的根本就";
        return new ResponseEntity<String>(result, HttpStatus.OK);
    }

    @GetMapping(value = "/bb")
    public String bb() throws Exception {
        String result = "我饿们是你的根本就";
        return result;
    }

    @RequestMapping("/zip")
    public String codewithzip(@RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName, HttpServletResponse response) throws Exception {
        String result = generatorMysqlFromExcelService.generatorMysqlFromExcel(file, tableName);
        String fileName = "由" + file.getName() + "生成的" + tableName + ".sql";
        byte[] data = generatorMysqlFromExcelService.generatorMysqlFromExcelZip(result, fileName);
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".zip");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        IOUtils.write(data, response.getOutputStream());
        return result;
    }

}
